import 'dart:async';
import 'package:e_reception_flutter/common_widgets/common_pack_up_keyboard_widget/common_pack_up_keyboard_widget.dart';
import 'package:e_reception_flutter/common_widgets/common_sliver_delegate/common_sliver_delegate.dart';
import 'package:e_reception_flutter/constants/constant.dart';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/singleton/user_repository/bean/user_response_bean.dart';
import 'package:e_reception_flutter/singleton/user_repository/mixin/user_stream_mixin.dart';
import 'package:e_reception_flutter/singleton/user_repository/user_repository.dart';
import 'package:e_reception_flutter/ui/company/company_detail/bean/company_detail_response_bean.dart';
import 'package:e_reception_flutter/ui/company/company_detail/event/change_tab_event.dart';
import 'package:e_reception_flutter/ui/company/company_detail/widgets/company_detail_add_flat_button_widget.dart';
import 'package:e_reception_flutter/ui/company/company_detail/widgets/company_detail_filter_button_widget.dart';
import 'package:e_reception_flutter/ui/company/company_detail/widgets/company_detail_pages_widget.dart';
import 'package:e_reception_flutter/ui/company/company_detail/widgets/company_detail_tabs_widget.dart';
import 'package:e_reception_flutter/ui/company/company_switch/bean/company_switch_list_bean.dart';
import 'package:e_reception_flutter/ui/login/login_bean/login_search_organization_bean.dart';
import 'package:e_reception_flutter/utils/app_monitoring_class.dart';
import 'package:e_reception_flutter/utils/app_overall_distinguish.dart';
import 'package:e_reception_flutter/utils/router_utils.dart';
import 'package:e_reception_flutter/utils/screen_utils.dart';
import 'package:e_reception_flutter/utils/vg_tool_utils.dart';
import 'package:e_reception_flutter/vg_widgets/vg_mixin/navigator_page_mixin.dart';
import 'package:e_reception_flutter/vg_widgets/vg_place_holder_status_widget/vg_place_holder_status_widget.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:vg_base/vg_arch_lib.dart';
import 'package:vg_base/vg_evnet_bus_lib.dart';
import 'package:vg_base/vg_sp_lib.dart';
import 'package:vg_base/vg_string_util_lib.dart';
import 'package:vg_flutter_base_moudle/vg_moudle_widget_lib.dart';
import '../../app_main.dart';
import 'bean/independent_company_basic_info_bean.dart';
import 'company_detail_view_model.dart';
import 'enterprise_detail_page.dart';
import 'event/refresh_company_detail_page_event.dart';
import 'widgets/company_detail_info_widget.dart';
import 'widgets/company_detail_search_list_widget.dart';
import 'package:extended_nested_scroll_view/extended_nested_scroll_view.dart'
    as extended;
import 'widgets/company_detail_top_bar_widget.dart';

/// 企业主页
///
/// @author: zengxiangxi
/// @createTime: 1/7/21 5:51 PM
/// @specialDemand:
class CompanyDetailPage extends StatefulWidget {
  ///路由名称
  static const String ROUTER = "CompanyDetailPage";

  final String gps;

  const CompanyDetailPage({Key key, this.gps}) : super(key: key);

  @override
  CompanyDetailPageState createState() => CompanyDetailPageState();

  ///跳转方法
  static Future<dynamic> navigatorPush(BuildContext context,String gps) {
    return RouterUtils.routeForFutureResult(
      context,
      CompanyDetailPage(gps:gps),
      routeName: CompanyDetailPage.ROUTER,
    );
    //     .then((value) {
    //   //每次返回都走一边首页刷新打卡数字接口
    //   VgEventBus.global.send(new ClearIndexCompanyInfoEvent(true));
    // });
  }
}

class CompanyDetailPageState extends BaseState<CompanyDetailPage>
    with TickerProviderStateMixin, NavigatorPageMixin, UserStreamMixin {
  GlobalKey morePopKey;

  TabController _tabController;

  List<GroupPersonCntBean> _tabsList;

  int _currentTabPositon = 0;

  ScrollController _scrollController;

  UserDataBean _user;

  CompanyDetailViewModel _viewModel;

  bool isFirst = true;

  ///刷新各列表
  StreamController<String> refreshStreamController;

  ///是否显示查询页
  ValueNotifier<String> _searchPageValueNotifier;

  UniqueKey refreshKey = UniqueKey();

  StreamController _tabsChangeStreamController;

  Stream get tabsChangeStream => _tabsChangeStreamController?.stream;

  CompanyDetailFilterNotification filterNotification;

  ValueNotifier<String> singleCompanyTitleValueNotifier;

  CompanyBasicInfoBean companyBasicInfoBean;

  StreamSubscription eventStreamSubscription;

  StreamSubscription changeTabStreamSubscription;

  List<OrgInfoListBean> orgSwitchInfoList;

  CompanySwitchListBean companySwitchListBean;

  StreamSubscription numBarStreamSubscription;

  String defaultgps;

  ///获取state
  static CompanyDetailPageState of(BuildContext context) {
    final CompanyDetailPageState result =
        context.findAncestorStateOfType<CompanyDetailPageState>();
    return result;
  }

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
    defaultgps = widget?.gps;
    companySwitchListBean = CompanySwitchListBean();
    orgSwitchInfoList = List<OrgInfoListBean>();
    companyBasicInfoBean = CompanyBasicInfoBean();
    morePopKey = GlobalKey();
    _viewModel = CompanyDetailViewModel(this, () {
      refreshKey = UniqueKey();
    }, defaultgps);

    _viewModel?.valueNotifier?.addListener(() {
      orgSwitchInfoList = _viewModel?.valueNotifier?.value;
      setState(() {});
    });
    _viewModel?.searchOrganization(
        context, UserRepository.getInstance().getPhone());

    singleCompanyTitleValueNotifier = ValueNotifier(null);
    //获取新接口的公司数据
    _viewModel?.groupInfoCompanyBasic?.addListener(() {
      if (_viewModel.groupInfoCompanyBasic.value != null) {
        companyBasicInfoBean = _viewModel?.groupInfoCompanyBasic?.value;
      }
    });
    filterNotification = CompanyDetailFilterNotification();
    //自定切换到员工分组
    _viewModel?.groupInfoValueNotifier?.addListener(() {
      if (_viewModel.groupInfoValueNotifier.value != null) {
        _firstChangeStaffClassify();
      }
    });
    //获取切换列表数据
    // _viewModel?.companyValueNotifier?.addListener(() {
    //   companySwitchListBean = _viewModel?.companyValueNotifier?.value;
    //   setState(() { });
    // });
    // _viewModel?.queryCompanyListData(context);
    //过滤更新时，随便更新下详情
    filterNotification?.companyDetailFilterValueNotifier?.addListener(() {
      _currentTabPositon = 0;
      _viewModel.getTopInfoHttp();
      _viewModel.getCompanyTopInfoHttp();
    });

    refreshStreamController = StreamController.broadcast();
    _searchPageValueNotifier = ValueNotifier(null);
    //todo待优化
    _tabsChangeStreamController = StreamController.broadcast();
    _tabController = TabController(length: _tabsList?.length ?? 0, vsync: this);
    _scrollController = ScrollController()..addListener(_scrollListener);
    _viewModel.getTopInfoCache();
    _viewModel.getTopInfoHttp();
    _viewModel.getCompanyTopInfoHttp();
    // addPageListener(onPop: () {
    //   _noticeRefreshHttp();
    // });
    addUserStreamListen((value) {
      _tabController?.index = 0;
      noticeRefreshHttp();
    });
    //观察者模式,监听接口是否使用
    eventStreamSubscription =
        VgEventBus.global.on<RefreshCompanyDetailPageEvent>().listen((event) {
      // _viewModel?.getTopInfoHttp();
          if("主动刷新下公司顶部信息" == (event?.msg??"")){
            _viewModel?.getTopInfoHttp();
            return;
          }
      setState(() {
        // _currentTabPositon = 0;
        _viewModel?.getTopInfoHttp();
        refreshStreamController.add(companyBasicInfoBean?.companyid);
        _tabLastTimeList();
      });
    });

    //观察者模式,监听切换类型
    changeTabStreamSubscription =
        VgEventBus.global.on<ChangeTabEvent>().listen((event) {
          //02学员 03家长 04员工
          if("02" == (event?.type??"")){
            changeToStudent();
          }
          if("03" == (event?.type??"")){
            changeToParent();
          }
          if("04" == (event?.type??"")){
            changeToStaff();
          }
        });

    numBarStreamSubscription =
        VgEventBus.global.on<CompanyNumBarEventMonitor>().listen((event) {
      _viewModel?.getTopInfoHttp();
      if (event?.delete ?? true) {
        refreshStreamController.add(companyBasicInfoBean?.companyid);
      }
      setState(() {});
    });
    // _attendanceStreamSubscription = VgEventBus.global.on<ArtificialAttendanceUpdateEvent>().listen((event) {
    //   refreshStreamController.add(null);
    //   setState(() { });
    // });
  }

  void _scrollListener() {
    if (_scrollController.offset > 20) {
      singleCompanyTitleValueNotifier.value =
          _viewModel?.groupInfoValueNotifier?.value?.companyInfo?.companynick;
    } else {
      singleCompanyTitleValueNotifier.value = null;
    }
  }

  @override
  void dispose() {
    _scrollController?.removeListener(_scrollListener);
    _scrollController?.dispose();
    _tabController?.dispose();
    refreshStreamController?.close();
    _searchPageValueNotifier?.dispose();
    _tabsChangeStreamController?.close();
    filterNotification?.dispose();
    singleCompanyTitleValueNotifier?.dispose();
    eventStreamSubscription?.cancel();
    numBarStreamSubscription?.cancel();
    changeTabStreamSubscription?.cancel();
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    // _viewModel?.getTopInfoHttp(fromPullRefresh: true);
    _user = UserRepository.getInstance().of(context);
  }

  ///造成分组重置（因为Key不同 重建列表，后期可以优化 判断分组不同情况才重置Key）
  void noticeRefreshHttp() {
    _viewModel?.getTopInfoHttp();
    _viewModel.getCompanyTopInfoHttp();
    print("企业详情页面更新");
    if (!refreshStreamController.isClosed) {
      refreshStreamController?.add(companyBasicInfoBean?.companyid);
    }
    // Future.delayed(Duration(milliseconds: 100), () {
    //   if (!refreshStreamController.isClosed) {
    //     refreshStreamController?.add(companyBasicInfoBean?.companyid);
    //   }
    // });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: false,
      resizeToAvoidBottomPadding: false,
      backgroundColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
      body: CommonPackUpKeyboardWidget(
          child: ScrollConfiguration(
              behavior: MyBehavior(),
              child: _toValueListenableBuilderWidget())),
    );
  }

  Widget _toValueListenableBuilderWidget() {
    return ValueListenableBuilder(
      valueListenable: _viewModel?.groupInfoValueNotifier,
      builder:
          (BuildContext context, CompanyDetailDataBean infoBean, Widget child) {
        // if (infoBean != null && isFirst) {
        //   isFirst = false;
        _tabsList = infoBean?.groupPersonCnt;
        GroupPersonCntBean groupPersonCntBean = GroupPersonCntBean();
        _tabsList?.forEach((element) {
          if (element?.groupName == "特别关注" && element?.cnt == 0) {
            groupPersonCntBean = element;
          }
        });
        _tabsList?.remove(groupPersonCntBean);
        int compCurrentPositon;
        if (_currentTabPositon >= (_tabsList?.length ?? 0)) {
          compCurrentPositon = (_tabsList?.length ?? 0) - 1;
          _currentTabPositon = 0;
        } else {
          compCurrentPositon = _currentTabPositon;
        }
        if (compCurrentPositon < 0) {
          compCurrentPositon = 0;
        }
        _tabController.removeListener(_tabListener);
        _tabController = TabController(
            length: _tabsList?.length ?? 0,
            initialIndex: compCurrentPositon,
            vsync: this)
          ..addListener(_tabListener);
        // }

        return _toMainColumnWidget(infoBean);
      },
    );
  }

  void _tabLastTimeList() {
    //选择分类默认选择
    SharePreferenceUtil.getString(KEY_LAST_ADD_USER_TYPE +
            UserRepository.getInstance().getCacheKeySuffix())
        .then((groupid) {
      if (StringUtils.isNotEmpty(groupid)) {
        for (int i = 0; i < _tabsList?.length; i++) {
          if (_tabsList[i]?.groupid?.contains(groupid)) {
            _tabController?.index = i;
            _tabListener();
          }
        }
      }
    });
  }

  void _tabListener() {
    _currentTabPositon = _tabController?.index;
    _tabsChangeStreamController.add(null);
    setState(() {});
  }

  Widget _toPlaceHolderWidget(CompanyDetailDataBean infoBean) {
    return ValueListenableBuilder(
      valueListenable: _viewModel?.statusValueNotifier,
      builder:
          (BuildContext context, PlaceHolderStatusType value, Widget child) {
        return VgPlaceHolderStatusWidget(
          loadingStatus: value == PlaceHolderStatusType.loading,
          errorStatus: value == PlaceHolderStatusType.error,
          errorOnClick: () => _viewModel.getTopInfoHttp(),
          loadingOnClick: () => _viewModel.getTopInfoHttp(),
          child: child,
        );
      },
      child: Stack(key: refreshKey, fit: StackFit.expand, children: [
        _toNestScrollWidget(infoBean),
        CompanyDetailSearchListWidget(
          searchPageValueNotifier: _searchPageValueNotifier,
        ),
        if (AppOverallDistinguish.comefromAiOrWeStudy())
          Positioned(
            right: 0,
            left: 0,
            bottom: 50,
            child: CompanyDetailAddFlatButtonWidget(
              onRefresh: () {
                _viewModel?.getTopInfoHttp();
              },
              role: infoBean?.companyInfo?.type,
              groupid: (infoBean?.groupPersonCnt?.length ?? 0) != 0
                  ? infoBean?.groupPersonCnt[_currentTabPositon]?.groupid
                  : "",
            ),
          )
      ]),
    );
  }

  Widget _toMainColumnWidget(CompanyDetailDataBean infoBean) {
    return Stack(
      children: [
        Column(
          children: <Widget>[
            CompanyDetailTopBarWidget(
              companyInfoBean: infoBean?.companyInfo,
              onRefresh: () {
                // _viewModel?.getTopInfoHttp();
              },
              orgSwitchInfoList: orgSwitchInfoList,
              companySwitchListBean: companySwitchListBean,
            ),
            Expanded(
              child: _toPlaceHolderWidget(infoBean),
            ),
            // CompanyDetailBottomSettingWidget(
            //   user: _user,
            // )
          ],
        ),
        if (UserRepository.getInstance()?.userData?.user?.changeflg == "00" &&
            (UserRepository.getInstance().companyList?.length ?? 0) > 1)
          _recognitionBubbleDialog(),
      ],
    );
  }

  Widget _recognitionBubbleDialog() {
    return Positioned(
      top: ScreenUtils.getStatusBarH(AppMain.context) + 40,
      left: (VgToolUtils.getScreenWidth() / 2) - 35,
      child: Column(
        children: <Widget>[
          Container(
              // padding: const EdgeInsets.only(right: 30),
              child: Image.asset(
            "images/triangle_bubble_box.png",
            height: 6,
            width: 12,
            color: ThemeRepository.getInstance().getMinorYellowColor_FFB714(),
          )),
          ClipRRect(
            borderRadius: BorderRadius.circular(4),
            child: Container(
              height: 28,
              width: 70,
              color: ThemeRepository.getInstance().getMinorYellowColor_FFB714(),
              child: Center(
                child: Text(
                  "点击切换",
                  style: TextStyle(
                      color: ThemeRepository.getInstance()
                          .getBgOrSplitColor_191E31(),
                      fontSize: 12),
                  textAlign: TextAlign.center,
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _toNestScrollWidget(CompanyDetailDataBean infoBean) {
    return extended.NestedScrollView(
      controller: _scrollController,
      physics: BouncingScrollPhysics(),
      innerScrollPositionKeyBuilder: () {
        return Key(_tabsList?.elementAt(_currentTabPositon)?.groupid);
      },
      headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) {
        return [
          // SliverToBoxAdapter(
          //   child: SizedBox(
          //     height: 12,
          //   ),
          // ),
          SliverToBoxAdapter(
            child: GestureDetector(
              behavior: HitTestBehavior.translucent,
              onTap: () {
                // if(!AppOverallDistinguish.comefromAiOrWeStudy()){return;}
                EnterpriseDetailPage.navigatorPush(context, defaultgps, itemBean: companyBasicInfoBean);
              },
              child: CompanyDetailInfoWidget(
                companyBasicInfoBean: companyBasicInfoBean,
                infoBean: infoBean,
                popKey: morePopKey,
                  defaultgps:defaultgps
              ),
            ),
          ),
          // SliverToBoxAdapter(child: CompanyDetailCardInfoWidget(infoBean:infoBean)),
          // SliverToBoxAdapter(
          //   child: SizedBox(
          //     height: 20,
          //   ),
          // ),
          // SliverToBoxAdapter(child: CompanyDetailTitleSplitWidget()),
          // SliverToBoxAdapter(
          //   child: SizedBox(
          //     height: 15,
          //   ),
          // ),
          // SliverPadding(
          //   padding: const EdgeInsets.only( bottom: 6),
          //   sliver: SliverToBoxAdapter(
          //     child: ValueListenableBuilder(
          //       valueListenable: _searchPageValueNotifier,
          //       builder: (BuildContext context, String searchStr, Widget child) {
          //        return  CommonSearchBarWidget(
          //          hintText: "搜索姓名",
          //          key: ValueKey(_searchStr == searchStr?.trim()),
          //          initContent: searchStr?.trim(),
          //          onSubmitted: (String searchStr) {
          //            //避免自己更新重置
          //            _searchStr = searchStr?.trim();
          //            _searchPageValueNotifier.value = searchStr?.trim();
          //          },
          //        );
          //       },
          //     ),
          //   ),
          // ),
          //   SliverPersistentHeader(
          //   pinned: true,
          //   key: UniqueKey(),
          // delegate: CommonSliverPersistentHeaderDelegate(
          //   child: _toNetworkStatusWidget(), maxHeight: 50
          // )
          // ),
          SliverPersistentHeader(
            pinned: true,
            key: UniqueKey(),
            delegate: CommonSliverPersistentHeaderDelegate(
                maxHeight: 50,
                minHeight: 50,
                child: CompanyDetailTabsWidget(
                  tabController: _tabController,
                  tabsList: _tabsList,
                )),
          ),
          if ((infoBean?.noFaceCnt ?? 0) != 0 &&
              AppOverallDistinguish?.enableFaceRecognition())
            SliverToBoxAdapter(child: _toNetworkStatusWidget(infoBean)),
        ];
      },
      body: CompanyDetailPagesWidget(
        currentCompanyId: companyBasicInfoBean?.companyid,
        tabController: _tabController,
        tabsList: _tabsList,
      ),
    );
  }

  Widget _toNetworkStatusWidget(CompanyDetailDataBean infoBean) {
    return Visibility(
      visible: true,
      child: Container(
        color: Color(0x33F95355),
        height: 30,
        child: Row(
          children: [
            SizedBox(
              width: 15,
            ),
            Text(
              "有${infoBean?.noFaceCnt ?? 0}位用户未上传人脸照片",
              style: TextStyle(
                fontSize: 12,
                color: Color(0xFFF95355),
              ),
            ),
            Spacer(),
          ],
        ),
      ),
    );
  }

  ///是否需要切换员工分组
  bool isNeedChangeStaffClassify = false;

  ///首次切换员工分组
  void _firstChangeStaffClassify() {
    if (isNeedChangeStaffClassify) {
      return;
    }
    isNeedChangeStaffClassify = true;
    changeToStaff();
  }

  void changeToParent(){
    final List<GroupPersonCntBean> groupList =
        _viewModel?.groupInfoValueNotifier?.value?.groupPersonCnt;
    if (groupList == null || groupList.isEmpty) {
      return;
    }
    for (int i = 0; i < groupList.length; i++) {
      if (groupList.elementAt(i).isParent()) {
        _changeTab(i);
        break;
      }
    }
  }

  void changeToStudent(){
    final List<GroupPersonCntBean> groupList =
        _viewModel?.groupInfoValueNotifier?.value?.groupPersonCnt;
    if (groupList == null || groupList.isEmpty) {
      return;
    }
    for (int i = 0; i < groupList.length; i++) {
      if (groupList.elementAt(i).isStudent()) {
        _changeTab(i);
        break;
      }
    }
  }

  void changeToStaff(){
    final List<GroupPersonCntBean> groupList =
        _viewModel?.groupInfoValueNotifier?.value?.groupPersonCnt;
    if (groupList == null || groupList.isEmpty) {
      return;
    }
    for (int i = 0; i < groupList.length; i++) {
      if (groupList.elementAt(i).isStaff()) {
        _changeTab(i);
        break;
      }
    }
  }

  void _changeTab(final int staffPositon) {
    if (staffPositon <= 0 || _tabController.length >= staffPositon) {
      return;
    }
    Future.delayed(Duration(milliseconds: 100), () {
      _tabController.animateTo(staffPositon,
          duration: const Duration(milliseconds: 10), curve: Curves.linear);
    });
  }
}
